export interface Message {
    name: string;
    data: any;
}

export class MessageServer {
    private listeners: { [name: string]: ((data: any) => void)[] } = {};
    private channel: MessageChannel = new MessageChannel();

    constructor(public targetWindow: Window) {
        targetWindow.addEventListener('message', (event) =>
            this.handleConnectionRequest(event),
        );
    }

    /**
     * 注册消息接收的处理函数
     * @param name - 消息名称
     * @param callback - 消息处理函数
     */
    public onMessage(name: string, callback: (data: any) => void) {
        if (!this.listeners[name]) {
            this.listeners[name] = [];
        }
        this.listeners[name].push(callback);
    }

    // 发送消息给客户端
    public sendMessage(name: string, data: any) {
        const port1 = this.channel.port1;
        if (!port1) {
            console.error('Port not established.');
            return;
        }
        console.log('server send message', name, data);
        port1.postMessage({ name: name, data: data });
    }

    // 处理客户端的连接请求
    private handleConnectionRequest(event: MessageEvent) {
        if (!this.channel) {
            throw new Error('MessageChannel is null');
        }
        if (event.data !== 'CONNECT') {
            return;
        }
        console.log('server handle');
        // 发送端口给客户端
        this.targetWindow.postMessage({ type: 'PORT', port: this.channel.port2 }, '*', [
            this.channel.port2,
        ]);

        // 监听消息
        this.channel.port1.addEventListener('message', this.handleMessage.bind(this));
        this.channel.port1.start();
    }

    /**
     * 接收消息并调用已注册的处理函数
     * @param event - 传递的事件对象
     */
    // 处理接收到的消息
    private handleMessage(event: MessageEvent) {
        console.log('Server received message:', event.data);
        const message: Message = event.data;
        if (this.listeners[message.name]) {
            this.listeners[message.name].forEach((callback) => callback(message.data));
        }
    }
}
